﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SimpleContainer
{
    public class SimpleContainerWebRequestLifetimeModule : IHttpModule
    {
        private static readonly object _Key = new object();


        internal static SynchronizedDictionary<string, object> GetInstances()
        {
            var items = HttpContext.Current.Items;
            if (items.Contains(_Key))
            {
                return (SynchronizedDictionary<string, object>)items[_Key];
            }
            lock (items)
            {
                if (items.Contains(_Key))
                {
                    return (SynchronizedDictionary<string, object>)items[_Key];
                }
                var res = new SynchronizedDictionary<string, object>();
                items.Add(_Key, res);
                return res;
            }
        }

        public void Init(HttpApplication context)
        {
            context.EndRequest += HandleEndRequest; 
        }

        private static void HandleEndRequest(object sender, EventArgs e)
        {
            var items = HttpContext.Current.Items;
            if (items.Contains(_Key))
            {
                var instances = (IDictionary<string, object>)items[_Key];
                try
                {
                    foreach (var i in instances.Values)
                    {
                        var id = i as IDisposable;
                        if (id != null)
                        {
                            id.Dispose();
                        }
                    }
                }
                finally
                {
                    items.Remove(_Key);
                }
            }
        }

        public void Dispose()
        {
            //context.EndRequest -= HandleEndRequest; 
        }

    }
}
